package handler

import (
	"encoding/json"
	"fmt"
	"github.com/Shopify/sarama"
	"week13/errors"
	"week13/internal/biz/deal"
	"week13/internal/biz/income"
	"week13/internal/job"
	"week13/log"
)
//订单收入创建job
type IncomeCreateJob struct {
}
func (IncomeCreateJob) Setup(_ sarama.ConsumerGroupSession ) error   { return nil }
func (IncomeCreateJob) Cleanup(_ sarama.ConsumerGroupSession ) error { return nil }
func (cj IncomeCreateJob) ConsumeClaim(sess sarama.ConsumerGroupSession , claim sarama.ConsumerGroupClaim) error {
	for msg := range claim.Messages() {
		log.Info("*******Message topic:%q partition:%d offset:%d\n", msg.Topic, msg.Partition, msg.Offset)
		err := cj.Run(msg.Value)
		if err !=nil {
			fmt.Errorf("deal msg:%+v,err:%s",msg,err.Error())
		}
		sess.MarkMessage(msg, "")
	}
	return nil
}


func (cj IncomeCreateJob) Run(jsonData []byte) error  {
	if len(jsonData) <1{
		return errors.NewIllegalParam("参数错误")
	}
	msg := job.IncomeCreateMessege{}
	err := json.Unmarshal(jsonData,&msg)

	if err != nil {
		return errors.NewIllegalParam(err.Error())
	}
	if msg.DealId < 1{
		return errors.NewIllegalParam("dealId < 1")
	}
	dealData, err := deal.FindOne(deal.DealDTO{DealId: msg.DealId})
	if err != nil {
		return err
	}
	//ok := deal.DealFinish(dealData)
	//if !ok {
	//	return nil
	//}
	amount := float64(dealData.Price)*0.1
	incomeDto := income.IncomeDTO{
		Amount:     int(amount),
		DealId:     dealData.DealId,
		AgentId:    dealData.AgentId,
		Rate:       10,
		SettleTime: dealData.GenTime+7*86400,
		State:      0,
		BizType:    1,
	}
	_, err = income.CreateIncome(incomeDto)
	if err !=nil {
		return err
	}
	return nil
}